﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Media.DirectShow.Filters;

namespace System.Windows.Media.DirectShow
{
    public class AsyncReaderStream : MemoryStream
    {

        private ManualResetEvent requestEvent = new ManualResetEvent(false);

        public AsyncReaderStream(IAsyncReader reader)
        {
            this.Reader = reader;
            reader.RequestCompleted += new EventHandler<ReaderAsyncCompletedEventArgs>(reader_RequestCompleted);
        }

        public IAsyncReader Reader
        {
            get;
            private set;
        }

        public void AppendSample(IMediaSample sample)
        {
            lock (this)
            {
                long p = this.Position;
                base.Seek(0, SeekOrigin.End);
                this.Write(sample.Data, 0, (int)sample.Length);
                this.Position = p;

                requestEvent.Set();
            }
        }

        protected bool GetHasAvailableData(int count)
        {
            return (this.Position + count <= this.Length);
        }

        protected bool IsFilterRunning
        {
            get
            {
                return ((IPin)this.Reader).Filter.State != FilterState.Stopped;
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            requestEvent.Set();
        }

        public void ClearToPosition()
        {
            lock (this)
            {
                byte[] buffer = this.GetBuffer();
                long diff = (this.Length - this.Position);

                // Traslate buffer to the begin
                Buffer.BlockCopy(buffer, (int)this.Position, buffer, 0, (int)diff);
                this.SetLength(diff);
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            while (true)
            {
                bool canRead;
                lock (this)
                {
                    canRead = this.CanRead && this.GetHasAvailableData(count);
                    if (canRead) break;
                    requestEvent.Reset();
                }

                this.RequestNextSample();
                requestEvent.WaitOne();
            }
            lock (this)
                return base.Read(buffer, offset, count);
        }

        private void RequestNextSample()
        {
            this.Reader.Request(this.Length, this.Length + ((BasePin)this.Reader).Allocator.Properties.BufferSize, null);
        }

        public override long Seek(long offset, SeekOrigin loc)
        {
            long dest = 0;
            switch (loc)
            {
                case SeekOrigin.Begin:
                    dest = offset;
                    break;
                case SeekOrigin.Current:
                    dest = this.Position + offset;
                    break;
                case SeekOrigin.End:
                    throw new NotSupportedException();
            }

            while (true)
            {
                bool canRead;
                lock (this)
                {
                    canRead = this.CanRead && dest <= this.Length;
                    if (canRead) break;
                    requestEvent.Reset();
                }
                this.RequestNextSample();

                requestEvent.WaitOne();
            }


            lock (this)
                return base.Seek(offset, loc);
        }

        private void reader_RequestCompleted(object sender, ReaderAsyncCompletedEventArgs e)
        {
            lock (this)
                requestEvent.Set();
        }
    }
}
